package com.houzehui.mncommodity.controller;


import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.houzehui.mncommodity.config.JwtUtils;
import com.houzehui.mncommodity.config.MsgResult;
import com.houzehui.mncommodity.config.PDFUtils;
import com.houzehui.mncommodity.config.WebUtils;
import com.houzehui.mncommodity.entity.City;
import com.houzehui.mncommodity.entity.Commodity;
import com.houzehui.mncommodity.entity.Commoditypromotion;
import com.houzehui.mncommodity.entity.User;
import com.houzehui.mncommodity.service.ICommodityService;
import com.houzehui.mncommodity.service.ICommoditypromotionService;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author houzehui
 * @since 2022-04-08
 */
@RestController
@RequestMapping("/commodity")
public class CommodityController {

    @Autowired
    ICommodityService iCommodityService;

    @Autowired
    ICommoditypromotionService iCommoditypromotionService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    KafkaTemplate kafkaTemplate;

    @GetMapping("list")
    public MsgResult list(Commodity commodity, @RequestParam(defaultValue = "1")int pageNum,@RequestParam(defaultValue = "3")int pageSize){

        PageHelper.startPage(pageNum,pageSize);

        QueryWrapper<Commodity> wrapper = new QueryWrapper<>();

        if(commodity.getName()!=null){
            wrapper.like("name",commodity.getName());
        }
        if(commodity.getPrice1()!=null){
            wrapper.ge("price",commodity.getPrice1());
        }
        if(commodity.getPrice2()!=null){
            wrapper.lt("price",commodity.getPrice2());
        }

        List<Commodity> list = iCommodityService.list(wrapper);

        for (Commodity commodity1 : list) {
            String Promotion="";
            String body = HttpRequest.get("http://localhost:84/city/getcity")
                    .form("provinceid", commodity1.getProvinceid())
                    .form("cityid", commodity1.getCityid())
                    .form("countyid", commodity1.getCountyid())
                    .execute().body();

            City city = JSON.parseObject(body, City.class);
            System.out.println(city);

            commodity1.setCityname(city.getProvincename()+city.getCityname1()+city.getCountyname());

            //查询促销
            QueryWrapper<Commoditypromotion> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("cid",commodity1.getId());

            List<Commoditypromotion> commoditypromotions = iCommoditypromotionService.getBaseMapper().selectList(queryWrapper);
            System.err.println(commoditypromotions);
            for (Commoditypromotion commoditypromotion : commoditypromotions) {
                String cid = HttpRequest.get("http://localhost:85/promotion/getpromotion")
                        .form("pid", commoditypromotion.getPid())
                        .execute().body();

                System.out.println(cid);
                Promotion+=cid+"/";

            }

            System.err.println("##############"+Promotion);
            commodity1.setPromotionname(Promotion);

        }

        PageInfo<Commodity> commodityPageInfo = new PageInfo<>(list);
        System.err.println(list);
        System.err.println(commodityPageInfo);
            return MsgResult.succeed(commodityPageInfo);
    }


    @GetMapping("pdf")
    public MsgResult pdf() throws Exception {
        List<Commodity> list = iCommodityService.list();
        for (Commodity commodity1 : list) {
            String Promotion="";
            String body = HttpRequest.get("http://localhost:84/city/getcity")
                    .form("provinceid", commodity1.getProvinceid())
                    .form("cityid", commodity1.getCityid())
                    .form("countyid", commodity1.getCountyid())
                    .execute().body();

            City city = JSON.parseObject(body, City.class);
            System.out.println(city);

            commodity1.setCityname(city.getProvincename()+city.getCityname1()+city.getCountyname());

            //查询促销
            QueryWrapper<Commoditypromotion> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("cid",commodity1.getId());

            List<Commoditypromotion> commoditypromotions = iCommoditypromotionService.getBaseMapper().selectList(queryWrapper);
            System.err.println(commoditypromotions);
            for (Commoditypromotion commoditypromotion : commoditypromotions) {
                String cid = HttpRequest.get("http://localhost:85/promotion/getpromotion")
                        .form("pid", commoditypromotion.getPid())
                        .execute().body();

                System.out.println(cid);
                Promotion+=cid+"/";

            }
            Promotion.substring(Promotion.lastIndexOf("/"));
            System.err.println("##############"+Promotion);
            commodity1.setPromotionname(Promotion);

        }

        PDFUtils.tableAndImg2pdf("d:/pic/commodity.pdf", null, "d:/pic/wang1.png", "列表", Arrays.asList("id", "产地", "促销"), new PDFUtils.PDFWriter() {
            @Override
            public void execute(PdfPTable pdfPTable, Font font) throws BadElementException, IOException {
                for (Commodity commodity : list) {
                    pdfPTable.addCell(new PdfPCell(new Paragraph(commodity.getId()+"",font)));
                    pdfPTable.addCell(new PdfPCell(new Paragraph(commodity.getCityname()+"",font)));
                    pdfPTable.addCell(new PdfPCell(new Paragraph(commodity.getPromotionname()+"",font)));

                }
            }
        });

        String path = UUID.randomUUID().toString()+".pdf";

        PDFUtils.markImage("d:/pic/wang1.png",
                new FileInputStream("d:/pic/commodity.pdf"),
                new FileOutputStream("d:/pic/"+path),
                "哈哈哈"

                );

        return MsgResult.succeed(path);

    }
    @Autowired
    JwtUtils jwtUtils;

    @GetMapping("getuserinfo")
    public MsgResult getuserinfo(){
        String header = WebUtils.getRequest().getHeader("token");
        String subject = jwtUtils.getTokenClaim(header).getSubject();

        User user = JSON.parseObject(subject, User.class);

        return MsgResult.succeed(user);

    }


    @GetMapping("getcityname")
    public MsgResult getcityname(){
        String body = HttpRequest.get("http://localhost:84/city/getcs")
                .execute().body();

        Object parse = JSON.parse(body);

        return MsgResult.succeed(parse);
    }

    @GetMapping("getproname")
    public MsgResult getproname(){
        String body = HttpRequest.get("http://localhost:85/promotion/getpro")
                .execute().body();

        Object parse = JSON.parse(body);

        return MsgResult.succeed(parse);
    }

    @GetMapping("getuuid")
    public MsgResult getuuid(){
        String uuid = UUID.randomUUID().toString();

        return MsgResult.succeed(uuid);
    }

    @PostMapping("addsave")
    public  MsgResult addsave(@RequestBody Commodity commodity) throws InterruptedException {
        System.err.println(commodity);
        String header = WebUtils.getRequest().getHeader("token");
        String subject = jwtUtils.getTokenClaim(header).getSubject();
        User user = JSON.parseObject(subject, User.class);
        System.err.println(user);
        if(user==null||user.getRole()==1){
            return MsgResult.fail("没有权限");
        }
        Thread.sleep(900);
        String uuid = commodity.getUuid();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("token" + uuid, null, 10, TimeUnit.SECONDS);
        if(!lock){
            return MsgResult.fail("请勿重复提交");
        }

    kafkaTemplate.send("test",uuid,JSON.toJSONString(commodity));
        return MsgResult.succeed();


    }

    @PostMapping("getxq")
    public MsgResult getxq(@RequestBody Commodity commodity){
        Integer id = commodity.getId();
        Commodity byId = iCommodityService.getById(id);
        QueryWrapper<Commoditypromotion> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cid",id);

        List<Commoditypromotion> commoditypromotions = iCommoditypromotionService.getBaseMapper().selectList(queryWrapper);
        List<Integer> collect = commoditypromotions.stream().map(s -> s.getPid()).collect(Collectors.toList());
        byId.setProidss(collect);

        return MsgResult.succeed(byId);


    }

}
